package com.qsl.juc.alternately_print;

import java.util.concurrent.CountDownLatch;

/**
 * 保证数字（字母）先输出
 */
public class AlternatelyPrintSynchronizedPlus {

    private static CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) {
        final Object obj = new Object();
        char[] digitalArr = "1234567".toCharArray();
        char[] letterArr = "ABCDEFG".toCharArray();

        new Thread(() -> {
            synchronized (obj) {
                for (char digital : digitalArr) {
                    System.out.print(digital);
                    latch.countDown();
                    try {
                        obj.notify();
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                obj.notify();       // 避免有线程未被唤醒，否则无法停止程序
            }
        }, "t1").start();       // 调用 start 后，线程只是进入就绪状态，线程调度器不一定选择此线程运行

        new Thread(() -> {

            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (obj) {
                for (char letter : letterArr) {
                    System.out.print(letter);
                    try {
                        obj.notify();
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                obj.notify();       // 避免有线程未被唤醒，否则无法停止程序
            }
        }, "t2").start();
    }
}
